/**
 * 本地存储工具类
 * 用于处理记住密码等功能的数据存储
 */

// 简单的编码/解码函数（注意：这不是真正的加密，仅用于防止明文存储）
const encode = (str) => {
  return btoa(encodeURIComponent(str))
}

const decode = (str) => {
  try {
    return decodeURIComponent(atob(str))
  } catch (e) {
    return ''
  }
}

// 记住密码相关的存储键
const REMEMBER_PASSWORD_KEY = 'rbac_remember_password'
const SAVED_USERNAME_KEY = 'rbac_saved_username'
const SAVED_PASSWORD_KEY = 'rbac_saved_password'

/**
 * 保存登录信息
 * @param {string} username 用户名
 * @param {string} password 密码
 * @param {boolean} remember 是否记住密码
 */
export const saveLoginInfo = (username, password, remember) => {
  if (remember) {
    localStorage.setItem(REMEMBER_PASSWORD_KEY, 'true')
    localStorage.setItem(SAVED_USERNAME_KEY, encode(username))
    localStorage.setItem(SAVED_PASSWORD_KEY, encode(password))
  } else {
    clearLoginInfo()
  }
}

/**
 * 获取保存的登录信息
 * @returns {object} 包含用户名、密码和记住密码状态的对象
 */
export const getSavedLoginInfo = () => {
  const remember = localStorage.getItem(REMEMBER_PASSWORD_KEY) === 'true'
  const username = remember ? decode(localStorage.getItem(SAVED_USERNAME_KEY) || '') : ''
  const password = remember ? decode(localStorage.getItem(SAVED_PASSWORD_KEY) || '') : ''
  
  return {
    username,
    password,
    remember
  }
}

/**
 * 清除保存的登录信息
 */
export const clearLoginInfo = () => {
  localStorage.removeItem(REMEMBER_PASSWORD_KEY)
  localStorage.removeItem(SAVED_USERNAME_KEY)
  localStorage.removeItem(SAVED_PASSWORD_KEY)
}

/**
 * 检查是否启用了记住密码
 * @returns {boolean}
 */
export const isRememberPasswordEnabled = () => {
  return localStorage.getItem(REMEMBER_PASSWORD_KEY) === 'true'
}
